<template>
  <div class="tree-container">
    <div class="tree-controls" v-if="showControls">
      <button @click="expandAll" class="control-btn expand-btn">展开全部</button>
      <button @click="collapseAll" class="control-btn collapse-btn">折叠全部</button>
    </div>

    <div class="tree-content">
      <TreeNode v-for="node in normalizedTreeData" :key="node.id" :node="node" :level="0"
        @node-click="handleNodeClick" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import TreeNode from './TreeNode.vue';

const props = defineProps({
  treeData: {
    type: [Array, Object],
    required: true
  },
  showControls: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(['node-click']);

// 标准化树数据，确保总是处理数组
const normalizedTreeData = computed(() => {
  console.log('tree data in panel', props.treeData);
  if (Array.isArray(props.treeData)) {
    return props.treeData.map(node => ({ ...node }));
  }
  return [{ ...props.treeData }];
});

// 初始化树数据，添加必要的属性
const initializeTreeData = (nodes) => {
  nodes.forEach(node => {
    node.isExpanded = node.isExpanded ?? true;

    if (node.children && node.children.length > 0) {
      initializeTreeData(node.children);
    }
  });
};

// 展开所有节点
const expandAll = () => {
  setAllNodesExpanded(normalizedTreeData.value, true);
};

// 折叠所有节点
const collapseAll = () => {
  setAllNodesExpanded(normalizedTreeData.value, false);
};

// 递归设置所有节点的展开状态
const setAllNodesExpanded = (nodes, isExpanded) => {
  nodes.forEach(node => {
    node.isExpanded = isExpanded;
    if (node.children && node.children.length > 0) {
      setAllNodesExpanded(node.children, isExpanded);
    }
  });
};

// 处理节点点击事件
const handleNodeClick = (node) => {
  emit('node-click', node);
};

// 初始化树数据
watch(normalizedTreeData, (newVal) => {
  initializeTreeData(newVal);
}, { immediate: true });
</script>

<style scoped>
.tree-container {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  border-radius: 1px;
  background-color: #153651;
  box-shadow: "5px 5px 15px 0px #242222"
}

.tree-controls {
  margin-bottom: 5px;
  display: flex;
  gap: 10px;
}

.control-btn {
  display: grid;
  align-items: center;
  grid-template-columns: 1fr;
}

.control-btn:hover {
  background-color: #e0e0e0;
}

.expand-btn {
  color: #153651;
}

.collapse-btn {
  color: #153651;
}

.tree-content {
  border-radius: 4px;
  padding: 1px;
  max-height: 590px;
  overflow-y: auto;
  background-color: #153651;
  scrollbar-color: #555 #153651;
}
</style>